package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.douwong.student.R;
import com.douwong.student.activity.FeaturesActivity;
import com.douwong.student.adapter.FeaturesAdapter;
import com.douwong.student.adapter.PrepareResourceAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.db.PrepareReaourceDBService;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.FeaturesBean;
import com.douwong.student.model.PrepareResource;
import com.douwong.student.model.PrepareTask;
import com.douwong.student.model.PrepareTitle;
import com.douwong.student.model.RequestAction;
import com.douwong.student.task.FeatureTaskList;
import com.douwong.student.task.PrepareListTask;
import com.douwong.student.task.PrepareResourceListTask;
import com.douwong.student.task.TaskListTask;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 资源碎片
 *
 * @author Administrator
 */
@SuppressLint("ValidFragment")
public class PrepareResourceFragment extends Fragment {
    private View view;
    private PullToRefreshListView prepare_res_listView;
    private PrepareResourceAdapter adapter;
    private PrepareResourceOnClick onClick;
    private FeaturesAdapter indroAdapter;
    private ArrayList<PrepareResource> list;
    private ArrayList<PrepareTitle> titleList;
    private ArrayList<FeaturesBean> indroList;
    private ArrayList<PrepareTask> taskList;
    private int sourceType = 0;
    private int titleSelect = 0;
    private LinearLayout prepare_ll, features_ll, job_ll, test_ll, courseware_ll, teaching_plan_ll, pic_ll, video_ll,
            other_ll;
    private int[] textView = new int[]{R.id.prepare_text, R.id.features_text, R.id.job_text, R.id.test_text,
            R.id.courseware_text, R.id.teaching_plan_text, R.id.pic_text, R.id.video_text, R.id.other_text};
    private BaseApplication app;
    private boolean isResource = true;
    private int i;
    private boolean isRefreshing = false;
    private boolean isDaodu = false;
    private boolean isTask = false;
    private ArrayList<PrepareResource> tempList = new ArrayList<PrepareResource>();
    private int visibleLastIndex = 0, currentPageIndex = 1;
    private final static String TAG = "PrepareResourceFragment";

    public PrepareResourceFragment() {
    }

    public PrepareResourceFragment(int i) {
        this.i = i;
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(CommonConfig.CHANGE_RESOURCE_STATE)) {
                list.clear();
                //				prepare_res_listView.setAdapter(adapter);
                list.addAll(PrepareReaourceDBService.getInstance(context).queryResource(0));
                Collections.sort(list);
                if (titleSelect == 0) {
                    tempList.clear();
                    tempList.addAll(list);
                } else {
                    getResourceList(titleSelect);
                }
                adapter.notifyDataSetChanged();
            }
        }

    };
    IntentFilter filter = new IntentFilter() {
        {
            addAction(CommonConfig.CHANGE_RESOURCE_STATE);
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        app = (BaseApplication) activity.getApplication();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.prepare_loaded_layout, null);
        list = new ArrayList<PrepareResource>();
        indroList = new ArrayList<FeaturesBean>();
        titleList = new ArrayList<PrepareTitle>();
        taskList = new ArrayList<PrepareTask>();
        getActivity().registerReceiver(receiver, filter);
        initView();
        updateData(RequestAction.INIT, 1, 0);
        tempList.addAll(list);
        adapter = new PrepareResourceAdapter(getActivity(), i, tempList);
        indroAdapter = new FeaturesAdapter(getActivity(), titleList);
        prepare_res_listView.setAdapter(adapter);
        showTextView(textView[0]);
        /*prepare_res_listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				prepare_res_listView.onScrollStateChanged(view, scrollState);
				if (isRefreshing)
					return;
				if (isResource) {
					if (titleSelect == 0) {
						int lastItemIndex = adapter.getCount();
						if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastItemIndex) {

							if (30 * (currentPageIndex) <= adapter.getCount()) {
								++currentPageIndex;
								updateData(RequestAction.LOADMROE, currentPageIndex, titleSelect);
								isRefreshing = true;
							}
						}
					}

				} else {
					int lastItemIndex = indroAdapter.getCount();
					if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastItemIndex) {

						if (30 * (currentPageIndex) <= indroAdapter.getCount()) {
							++currentPageIndex;
							updateIndroData(RequestAction.LOADMROE, currentPageIndex);
							isRefreshing = true;
						}
					}
				}

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				prepare_res_listView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
				visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
			}
		});*/
        prepare_res_listView.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (isRefreshing) {
                    return;
                }
                if (isResource){
                    if (titleSelect==0){
                        ++currentPageIndex;
                        updateData(RequestAction.LOADMROE, currentPageIndex, titleSelect);
                        isRefreshing = true;
                    }

                }else {
                    ++currentPageIndex;
                    updateIndroData(RequestAction.LOADMROE, currentPageIndex);
                    isRefreshing = true;

                }

            }
        });
        prepare_res_listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isDaodu) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), FeaturesActivity.class);
                    intent.putExtra("features", indroList.get(position - 1).getIntroInfo());
                    getActivity().startActivity(intent);
                    // PrepareTestDetailTask testTask = new
                    // PrepareTestDetailTask(
                    // 1);
                    // testTask.execute(String.valueOf(indroList.get(position -
                    // 1)
                    // .getId()));
                    // testTask.setDetailListener(new DetailNotify() {
                    //
                    // @Override
                    // public void notify(int stateCode, String content) {
                    // // TODO Auto-generated method stub
                    // Intent intent = new Intent();
                    // intent.setClass(getActivity(),
                    // FeaturesActivity.class);
                    // intent.putExtra("features", content);
                    // getActivity().startActivity(intent);
                    // }
                    // });
                } else if (isTask) {

                } else if (isResource) {
                    if (tempList.get(position - 1).isLoaded()) {
                        FileUtils.openFile(tempList.get(position - 1).getFilePath(), tempList.get(position - 1).getFileName(), getActivity());
                    }
                }
            }
        });
        prepare_res_listView.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                if (isResource) {
                    if (titleSelect == 0) {
                        updateData(RequestAction.REFRESH, 1, titleSelect);
                    } else {
                        getResourceList(titleSelect);
                        isRefreshing = false;
                        prepare_res_listView.onRefreshComplete();
                    }
                } else if (isDaodu) {
                    updateIndroData(RequestAction.REFRESH, 1);
                } else if (isTask) {
                    updateTaskData(RequestAction.REFRESH, 1);
                }

            }


        });
        return view;
    }

    public class PrepareResourceOnClick implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                // 全部
                case R.id.prepare_ll:
                    isResource = true;
                    isDaodu = false;
                    titleSelect = 0;
                    tempList.clear();
                    list.clear();
                    prepare_res_listView.setAdapter(adapter);
                    showTextView(textView[0]);
                    updateData(RequestAction.INIT, 1, 0);
                    break;
                // 导读
                case R.id.features_ll:
                    // titleSelect=1;
                    isDaodu = true;
                    isTask = false;
                    isResource = false;
                    indroList.clear();
                    showTextView(textView[1]);
                    prepare_res_listView.setAdapter(indroAdapter);
                    updateIndroData(RequestAction.INIT, 1);
                    break;
                // 任务
                case R.id.job_ll:
                    isResource = false;
                    isDaodu = false;
                    isTask = true;
                    taskList.clear();
                    // titleSelect=2;
                    showTextView(textView[2]);
                    prepare_res_listView.setAdapter(indroAdapter);
                    updateTaskData(RequestAction.INIT, 1);
                    break;
                // 试卷
                case R.id.test_ll:
                    isResource = false;
                    prepare_res_listView.setAdapter(indroAdapter);
                    indroAdapter.notifyDataSetChanged();
                    // titleSelect=3;
                    showTextView(textView[3]);
                    break;
                // 课件
                case R.id.courseware_ll:
                    isResource = true;
                    isDaodu = false;
                    titleSelect = 1;
                    // prepare_res_listView.setAdapter(adapter);
                    showTextView(textView[4]);
                    getResourceList(titleSelect);

                    // updateData(RequestAction.INIT, 1, 1);
                    break;
                // 教案
                case R.id.teaching_plan_ll:
                    // list.clear();
                    isResource = true;
                    isDaodu = false;
                    titleSelect = 2;
                    showTextView(textView[5]);
                    // prepare_res_listView.setAdapter(adapter);
                    // updateData(RequestAction.INIT, 1, 2);
                    break;
                // 图片
                case R.id.pic_ll:
                    isResource = true;
                    isDaodu = false;
                    titleSelect = 2;
                    showTextView(textView[6]);
                    // prepare_res_listView.setAdapter(adapter);
                    getResourceList(titleSelect);
                    // updateData(RequestAction.INIT, 1, 3);
                    break;
                // 影音
                case R.id.video_ll:
                    isResource = true;
                    isDaodu = false;
                    // list.clear();
                    titleSelect = 3;
                    showTextView(textView[7]);
                    getResourceList(titleSelect);
                    // prepare_res_listView.setAdapter(adapter);
                    // updateData(RequestAction.INIT, 1, 4);
                    break;
                // 其他
                case R.id.other_ll:
                    // list.clear();
                    titleSelect = 4;
                    isDaodu = false;
                    showTextView(textView[8]);
                    getResourceList(titleSelect);
                    // prepare_res_listView.setAdapter(adapter);
                    // updateData(RequestAction.INIT, 1, 5);
                    break;
                // 下载
                case R.id.load_text:
                    int position = (Integer) view.getTag();
                    break;
                default:
                    break;
            }
        }

    }

    private void getResourceList(int type) {
        tempList.clear();
        list.clear();
        if (BaseApplication.sUserBean != null) {
            list.addAll(PrepareReaourceDBService.getInstance(getActivity()).queryResource(0));
        } else {
            Toast.makeText(getActivity(), "请先登录！", Toast.LENGTH_LONG).show();
            return;
        }
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            String suffix = list.get(i).getAttaSuffix();
            if (type == 2) {
                if (suffix.equals("jpg") || suffix.equals("png")) {
                    tempList.add(list.get(i));
                    //					Log.e("tempList", tempList.size() + "");
                }
            } else if (type == 1) {
                if (suffix.equals("ppt")) {
                    tempList.add(list.get(i));
                }
            } else if (type == 3) {
                if (suffix.equals("mp4") || suffix.equals("avi") || suffix.equals("flv")) {
                    tempList.add(list.get(i));
                }
            } else if (type == 4) {
                if (!suffix.equals("jpg") && !suffix.equals("png") && !suffix.equals("ppt") && !suffix.equals("mp4")
                        && !suffix.equals("avi") && !suffix.equals("flv")) {
                    tempList.add(list.get(i));
                }

            }

        }
        adapter.notifyDataSetChanged();

    }

    private void initView() {
        prepare_ll = (LinearLayout) view.findViewById(R.id.prepare_ll);
        features_ll = (LinearLayout) view.findViewById(R.id.features_ll);
        job_ll = (LinearLayout) view.findViewById(R.id.job_ll);
        test_ll = (LinearLayout) view.findViewById(R.id.test_ll);
        courseware_ll = (LinearLayout) view.findViewById(R.id.courseware_ll);
        teaching_plan_ll = (LinearLayout) view.findViewById(R.id.teaching_plan_ll);
        pic_ll = (LinearLayout) view.findViewById(R.id.pic_ll);
        video_ll = (LinearLayout) view.findViewById(R.id.video_ll);
        other_ll = (LinearLayout) view.findViewById(R.id.other_ll);

        prepare_res_listView = (PullToRefreshListView) view.findViewById(R.id.prepare_resource_listview);
        prepare_res_listView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        onClick = new PrepareResourceOnClick();
        prepare_ll.setOnClickListener(onClick);
        features_ll.setOnClickListener(onClick);
        job_ll.setOnClickListener(onClick);
        test_ll.setOnClickListener(onClick);
        courseware_ll.setOnClickListener(onClick);
        teaching_plan_ll.setOnClickListener(onClick);
        pic_ll.setOnClickListener(onClick);
        video_ll.setOnClickListener(onClick);
        other_ll.setOnClickListener(onClick);
        showTextView(textView[0]);

    }

    private void showTextView(int id) {
        for (int i = 0; i < textView.length; i++) {
            if (id == textView[i]) {
                view.findViewById(id).setVisibility(View.VISIBLE);
            } else {
                view.findViewById(textView[i]).setVisibility(View.INVISIBLE);
            }

        }
    }

    protected void updateIndroData(final RequestAction action, int pageIndex) {
        titleList.clear();
        FeatureTaskList task = new FeatureTaskList(action, app);
        task.setWorkStautsListener(new WorkResultNotify<FeaturesBean>() {

            @Override
            public void notify(int stateCode, List<FeaturesBean> arryResult) {
                if (FeatureTaskList.NO_DATA == stateCode) {

                    // 加载更多时，出现异常或者没有多余数据，要将currentPageIndex回到加载数据前的一页
                    if (currentPageIndex > 1 && RequestAction.LOADMROE == action) {
                        --currentPageIndex;
                        ToastUtils.makeText(BaseApplication.mContext,"没有更多数据了");
                    }
                    if (arryResult == null && action != RequestAction.LOADMROE) {
                       // indroList.clear();

                    }

                } else if (PrepareListTask.REQUESTOK == stateCode) {
                    // 其他访问类型均需要清空当前数据，重新显示，加载更多是在原有的数据上增加
                    if (RequestAction.LOADMROE != action) {
                        indroList.clear();
                    }

                    if (arryResult != null) {
                        indroList.addAll(arryResult);
                        for (int i = 0; i < indroList.size(); i++) {
                            PrepareTitle title = new PrepareTitle();
                            title.setCreateTime(indroList.get(i).getCreatetime());
                            title.setName(indroList.get(i).getTitle());
                            title.setSubject(indroList.get(i).getMsName() + "\t" + indroList.get(i).getEuNickName());
                            titleList.add(title);
                        }
                    }
                }
                isRefreshing = false;
                prepare_res_listView.onRefreshComplete();
                indroAdapter.notifyDataSetChanged();
            }
        });
        task.execute(String.valueOf(pageIndex));

    }

    protected void updateData(final RequestAction action,final int pageIndex, int resourceType) {
        PrepareResourceListTask task = new PrepareResourceListTask(getActivity(), action, app);
        task.setWorkStautsListener(new WorkResultNotify<PrepareResource>() {

            @Override
            public void notify(int stateCode, List<PrepareResource> arryResult) {
                if (PrepareListTask.NO_DATA == stateCode) {

                    // 加载更多时，出现异常或者没有多余数据，要将currentPageIndex回到加载数据前的一页
                    if (currentPageIndex > 1 && RequestAction.LOADMROE == action) {
                        --currentPageIndex;
                        ToastUtils.makeText(BaseApplication.mContext,"没有更多数据了");
                    }

                    if (arryResult == null && action != RequestAction.LOADMROE) {
                     //   list.clear();

                    }

                } else if (PrepareListTask.REQUESTOK == stateCode) {
                    // 其他访问类型均需要清空当前数据，重新显示，加载更多是在原有的数据上增加
                    // if (RequestAction.LOADMROE != action) {
                    list.clear();
                    // }
                    if (arryResult != null && arryResult.size() > 0) {
                        tempList.clear();
                        list.addAll(arryResult);
                        Collections.sort(list);
                        tempList.addAll(list);
                    }
                }
                isRefreshing = false;
                prepare_res_listView.onRefreshComplete();
                prepare_res_listView.completeLoadMore();
                adapter.notifyDataSetChanged();
            }
        });

        if (BaseApplication.sUserBean == null) {
            isRefreshing = false;
            prepare_res_listView.onRefreshComplete();
        } else {
            task.execute(String.valueOf(pageIndex), String.valueOf(resourceType));
        }


    }

    protected void updateTaskData(final RequestAction action, int pageIndex) {
        titleList.clear();
        TaskListTask task = new TaskListTask(action, app);
        task.setWorkStautsListener(new WorkResultNotify<PrepareTask>() {

            @Override
            public void notify(int stateCode, List<PrepareTask> arryResult) {
                if (FeatureTaskList.NO_DATA == stateCode) {

                    // 加载更多时，出现异常或者没有多余数据，要将currentPageIndex回到加载数据前的一页
                    if (currentPageIndex > 1 && RequestAction.LOADMROE == action) {
                        --currentPageIndex;
                    }
                    if (arryResult == null && action != RequestAction.LOADMROE) {
                        taskList.clear();
                    }

                } else if (PrepareListTask.REQUESTOK == stateCode) {
                    // 其他访问类型均需要清空当前数据，重新显示，加载更多是在原有的数据上增加
                    if (RequestAction.LOADMROE != action) {
                        taskList.clear();
                    }

                    if (arryResult != null) {
                        taskList.addAll(arryResult);
                        for (int i = 0; i < taskList.size(); i++) {
                            PrepareTitle title = new PrepareTitle();
                            title.setCreateTime(taskList.get(i).getCreatetime());
                            title.setName(taskList.get(i).getTaskTitle());
                            title.setSubject(taskList.get(i).getMsName() + "\t" + taskList.get(i).getEuNickName());
                            titleList.add(title);
                            Log.e("title", title.getName() + "");
                        }
                    }

                }
                isRefreshing = false;
                prepare_res_listView.onRefreshComplete();
                indroAdapter.notifyDataSetChanged();
            }
        });
        task.execute(String.valueOf(pageIndex));

    }

    // public View getViewByPosition(int pos, ListView listView) {
    // final int firstListItemPosition = listView.getFirstVisiblePosition();
    // final int lastListItemPosition = firstListItemPosition
    // + listView.getChildCount() - 1;
    //
    // if (pos < firstListItemPosition || pos > lastListItemPosition) {
    // return listView.getAdapter().getView(pos, null, listView);
    // } else {
    // final int childIndex = pos - firstListItemPosition;
    // Log.e("firstListItemPosition", firstListItemPosition + "");
    // Log.e("lastListItemPosition", lastListItemPosition + "");
    // Log.e("childIndex", childIndex + "");
    // return listView.getChildAt(childIndex-1);
    // }
    // }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }
}
